<?php

namespace App\Listeners;

use Swof\Event\Listener;
use Swoole\Coroutine\Http\Client;
use Swoole\Timer;

class StartListener extends Listener
{
    protected $name = 'start';

    public function handle($args = [])
    {
        $server = $args[0];

        go(function () use ($server) {
            $config = config('server.route');

            $client = new Client($config['host'], $config['port']);

            $ret = $client->upgrade('/');

            if ($ret) {
                $client->push(json_encode([
                    'ip' => $server->getHost(),
                    'port' => $server->getPort(),
                    'method' => 'register',
                    'server_name' => $server->getServerName()
                ]));

                Timer::tick(3000, function (int $timerId) use ($client) {
                    $client->push('', WEBSOCKET_OPCODE_PING);
                });

            }
        });
    }
}